package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceCode;
import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.*;
import cn.tedu.csmall.product.pojo.dto.SpuAddNewDTO;
import cn.tedu.csmall.product.pojo.dto.SpuUpdateDTO;
import cn.tedu.csmall.product.pojo.entity.Detail;
import cn.tedu.csmall.product.pojo.entity.Spu;
import cn.tedu.csmall.product.pojo.vo.*;
import cn.tedu.csmall.product.service.ISpuService;
import cn.tedu.csmall.product.util.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SpuServiceImpl implements ISpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;

    /**
     * 插入一条spu数据
     * @param spuAddNewDTO
     */
    @Override
    public void addNew(SpuAddNewDTO spuAddNewDTO) {
        //根据DTO对象的品牌id获取品牌对象，判断该品牌是否存在
        BrandStandardVO queryByBrandId = brandMapper.getStandardById(spuAddNewDTO.getBrandId());
        log.debug("获取到的品牌对象："+queryByBrandId.toString());
        //如果不存在，抛出异常
        if(queryByBrandId==null){
            String message="添加失败，品牌不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        //如果存在，判断该品牌是否启用，如果未启用，抛出异常
        log.debug("品牌【{}】存在，开始查询是否启用！",queryByBrandId.getName());
        Integer enable = queryByBrandId.getEnable();
        if(enable==0){
            String message="添加失败，品牌【"+queryByBrandId.getName()+"】未启用！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //根据DTO对象的类别id获取类别对象，判断该类别是否存在
        CategoryStandardVO queryByCategoryId = categoryMapper.getCategoryStandardVO(spuAddNewDTO.getCategoryId());
        //如果不存在，抛出异常
        if(queryByCategoryId==null){
            String message="添加失败，类别不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        //如果存在，判断该类别是否启用，如果未启用，抛出异常
        log.debug("类别【{}】存在，开始查询是否启用！",queryByCategoryId.getName());
        enable = queryByCategoryId.getEnable();
        if(enable==0){
            String message="添加失败，类别【"+queryByCategoryId.getName()+"】未启用！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        // 判断查询到的类别的isParent是否为1
        if(queryByCategoryId.getIsParent()==1){
            // 是：抛出异常
            String message = "新增Spu失败，尝试绑定的类别包含子级类别，不允许使用此类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //根据DTO对象的类别id获取相册对象，判断该相册是否存在
        AlbumStandardVO queryByAlbumId = albumMapper.getAlbumStandardVO(spuAddNewDTO.getAlbumId());
        //如果不存在，抛出异常
        if(queryByAlbumId==null){
            String message="添加失败，相册不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("相册【{}】存在！",queryByAlbumId.getName());


        //创建spu对象，把DTO复制到spu对象中
        Spu spu=new Spu();
        BeanUtils.copyProperties(spuAddNewDTO,spu);

        //补充spu属性值：id
        //TODO 补全Spu对象的属性值（spuAddNewDTO,spu）

        spu.setId(IdUtils.getId());

        //补充spu属性值：brandName
        spu.setBrandName(queryByBrandId.getName());

        //补充spu属性值：categoryName
        spu.setCategoryName(queryByCategoryId.getName());

        //补充spu属性值：sales / commentCount / positiveCommentCount >>> 0
        spu.setSales(0);
        spu.setCommentCount(0);
        spu.setPositiveCommentCount(0);

        //补充spu属性值：isDelete / isPublished >>> 0
        spu.setIsDeleted(0);
        spu.setIsPublished(0);

        //补充spu属性值：isNewArrival / isRecommend >>> 自行决定
        spu.setIsNewArrival(0);
        spu.setIsRecommend(0);

        //补充spu属性值：isChecked >>> 0
        spu.setIsChecked(0);

        //补充spu属性值：checkUser / gmtCheck >>> null(不用赋值)

        //创建spuDetail对象，
        Detail detail=new Detail();

        //spuDetail设置spuId值
        detail.setSpuId(spu.getId());

        //spuDetail设置值detail值
        detail.setDetail(spuAddNewDTO.getDetail());

        //调用spuMapper的insert方法，获取返回值
        log.debug("准备插入spu数据");
        int rows = spuMapper.insert(spu);
        //如果返回值不为1，抛出异常
        if(rows!=1){
            String message="spu添加失败，系统繁忙，请稍后重试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("spu添加成功！");

        //调用spuDetailMapper的insert方法，获取返回值
        log.debug("准备插入spuDetail数据");
        rows= spuDetailMapper.insert(detail);
        //如果返回值不为1，抛出异常
        if(rows!=1){
            String message="spuDetail添加失败，系统繁忙，请稍后重试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("spuDetail添加成功！");
    }

    /**
     * 根据id删除spu
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据id删除spu】业务");
        SpuStandardVO spuStandardVO = spuMapper.getSpuStandardVO(id);
        if(spuStandardVO==null){
            String message="删除失败，数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int rows = spuMapper.deleteById(id);
        if(rows!=1){
            String message="删除spu失败，系统繁忙，请稍后重试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
        log.debug("删除spu成功！");
    }

    /**
     * 根据id逻辑删除spu
     * @param id
     */
    @Override
    public void setIsDelete(Long id) {
        log.debug("开始处理【根据id逻辑删除】业务");
        //根据id获取spuStandardVO对象
        SpuStandardVO spuStandardVO = spuMapper.getSpuStandardVO(id);
        //如果对象为null，抛出异常
        if(spuStandardVO==null){
            String message="删除失败，数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Integer isDeleted = spuStandardVO.getIsDeleted();
        if(isDeleted.equals(1)){
            String message="逻辑删除失败，该数据已经被逻辑删除！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Spu spu=new Spu();
        spu.setIsDeleted(1);
        spu.setId(id);
        int rows = spuMapper.updateById(spu);
        if(rows!=1){
            String message="逻辑删除spu失败，系统繁忙，请稍后重试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
        log.debug("逻辑删除spu成功！");
    }


    /**
     * 根据id恢复spu
     * @param id
     */
    @Override
    public void setUnIsDelete(Long id) {
        log.debug("开始处理【根据id恢复spu】业务");
        //根据id获取spuStandardVO对象
        SpuStandardVO spuStandardVO = spuMapper.getSpuStandardVO(id);
        //如果对象为null，抛出异常
        if(spuStandardVO==null){
            String message="删除失败，数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Integer isDeleted = spuStandardVO.getIsDeleted();
        if(isDeleted.equals(0)){
            String message="恢复失败，该数据已经被恢复！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Spu spu=new Spu();
        spu.setIsDeleted(0);
        spu.setId(id);
        int rows = spuMapper.updateById(spu);
        if(rows!=1){
            String message="恢复spu失败，系统繁忙，请稍后重试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
        log.debug("恢复spu成功！");
    }

    /**
     * 获取spu列表
     * @return
     */
    @Override
    public List<SpuListItemVO> list() {
        log.debug("开始处理【spu列表请求】");
        return spuMapper.list();
    }
}
